<!DOCTYPE html>
<html lang="en">

<!-- Head tag (contains Google-Analytics、Baidu-Tongji)-->
<head>
  <!-- Google Analytics -->
  

  <!-- Baidu Tongji -->
  
    <script type="text/javascript">
      // Originial
      var _hmt = _hmt || [];
      (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?cdf616a127124dd7ff798963125b304d";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
      })();
    </script>
  

  <!-- Baidu Push -->
  
    <script>
      (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
          bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
          bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
      })();
    </script>
  

  <meta charset="utf-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>

  <meta name="google-site-verification" content="lxDfCplOZbIzjhG34NuQBgu2gdyRlAtMB4utP5AgEBc"/>
  <meta name="baidu-site-verification" content="PpzM9WxOJU"/>

  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <meta name="description" content="It&#39;s an IT blog..."/>
  <meta name="keyword" content="zhuang,IT  blog,Blog"/>
  <link rel="shortcut icon" href="/img/avatar/java-head.png"/>

  <!-- Place this tag in your head or just before your close body tag. -->
  <script async="async" defer="defer" src="https://buttons.github.io/buttons.js"></script>

  
    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css"/>

    <!-- Custom CSS -->
    <link rel="stylesheet" href="/css/beantech.min.css"/>

    <!-- Pygments Highlight CSS -->
    <link rel="stylesheet" href="/css/highlight.css"/>
    <link rel="stylesheet" href="/css/widget.css"/>
    <link rel="stylesheet" href="/css/rocket.css"/>
    <link rel="stylesheet" href="/css/signature.css"/>
    <link rel="stylesheet" href="/css/catalog.css"/>
    <link rel="stylesheet" href="/css/livemylife.css"/>

    
      <!-- wave start -->
      <link rel="stylesheet" href="/css/wave.css"/>
      <!-- wave end -->
    

    
      <!-- top start (article top hot config) -->
      <link rel="stylesheet" href="/css/top.css"/>
      <!-- top end -->
    

    
      <!-- ThemeColor start -->
      <link rel="stylesheet" href="/css/scroll.css"/>
      <!-- ThemeColor end -->
    

    
      <!-- viewer start (Picture preview) -->
      <link rel="stylesheet" href="/css/viewer.min.css"/>
      <!-- viewer end -->
    

    
      <!-- Search start -->
      <link rel="stylesheet" href="/css/search.css"/>
      <!-- Search end -->
    

    
      <!-- ThemeColor start -->
      <link rel="stylesheet" href="/css/themecolor.css"/>
      <!-- ThemeColor end -->
    

    

    
  

  <!-- Custom Fonts -->
  <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
  <!-- Hux change font-awesome CDN to qiniu -->
  <link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" type="text/css">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <!-- Hux Delete, sad but pending in China <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link
  href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/ css'> -->

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]-->

  <!-- ga & ba script hoook -->
  <link rel="canonical" href="http://yoursite-url/cn/python/详解Python序列结构/">
  <title>
    
      python基础 &gt; 详解Python序列结构 - either thin | or die
    
  </title>
<meta name="generator" content="Hexo 5.4.0"></head>


<!-- hack iOS CSS :active style -->

	<body ontouchstart="" class="body--light body--dark">


		<!-- ThemeColor -->
		
		<!-- ThemeColor -->
<style type="text/css">
  .body--light {
    --light-mode: none;
    --dark-mode: block;
  }
  .body--dark {
    --light-mode: block;
    --dark-mode: none;
  }
  i.mdui-icon.material-icons.light-mode {
    display: var(--light-mode);
  }
  i.mdui-icon.material-icons.dark-mode {
    display: var(--dark-mode);
  }
</style>
<div class="toggle" onclick="document.body.classList.toggle('body--dark')">
  <i class="mdui-icon material-icons light-mode"></i>
  <i class="mdui-icon material-icons dark-mode"></i>
</div>
<script>
  //getCookieValue
  function getCookieValue(a) {
    var b = document.cookie.match('(^|[^;]+)\\s*' + a + '\\s*=\\s*([^;]+)');
    return b
      ? b.pop()
      : '';
  }
  let themeMode = 'dark';
  if (getCookieValue('sb-color-mode') && (getCookieValue('sb-color-mode') !== themeMode)) {
    let dbody = document.body.classList;
    themeMode === 'dark' ? dbody.remove('body--dark') : dbody.add('body--dark');
  }

  //setCookieValue
  var toggleBtn = document.querySelector(".toggle");
  toggleBtn.addEventListener("click", function () {
    var e = document.body.classList.contains("body--dark");
    var cookieString = e
      ? "dark"
      : "light";
    var exp = new Date();
    exp.setTime(exp.getTime() + 3 * 24 * 60 * 60 * 1000); //3天过期
    document.cookie = "sb-color-mode=" + cookieString + ";expires=" + exp.toGMTString() + ";path=/";
  });
</script>

		

		<!-- Gitter -->
		

		<!-- Navigation (contains search)-->
		<!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header page-scroll">
      <button type="button" class="navbar-toggle">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="/">平平淡淡</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <!-- Known Issue, found by Hux: <nav>'s height woule be hold on by its content. so, when navbar scale out, the <nav> will cover tags. also mask any touch event of tags, unfortunately. -->
    <div id="huxblog_navbar">
      <div class="navbar-collapse">
        <ul class="nav navbar-nav navbar-right">
          <li>
            <a href="/">首页</a>
          </li>

          
          
          
          
          <li>
            <a href="/archive/">
              
              归档
              
              
            </a>
          </li>
          
          
          
          <li>
            <a href="/tags/">
              
              标签
              
              
            </a>
          </li>
          
          
          
          <li>
            <a href="/categories/">
              
              分类
              
              
            </a>
          </li>
          
          
          
          <li>
            <a href="/about/">
              
              关于
              
              
            </a>
          </li>
          
          

          
          <li>
            <a class="popup-trigger">
              <span class="search-icon"></span>搜索</a>
          </li>
          

          <!-- LangSelect -->
          
        </ul>
      </div>
    </div>
    <!-- /.navbar-collapse -->
  </div>
  <!-- /.container -->
</nav>
<!-- progress -->
<div id="progress">
  <div class="line" style="width: 0%;"></div>
</div>

<script>
  // Drop Bootstarp low-performance Navbar Use customize navbar with high-quality material design animation in high-perf jank-free CSS3 implementation
  var $body = document.body;
  var $toggle = document.querySelector('.navbar-toggle');
  var $navbar = document.querySelector('#huxblog_navbar');
  var $collapse = document.querySelector('.navbar-collapse');

  $toggle.addEventListener('click', handleMagic)

  function handleMagic(e) {
    if ($navbar.className.indexOf('in') > 0) {
      // CLOSE
      $navbar.className = " ";
      // wait until animation end.
      setTimeout(function() {
        // prevent frequently toggle
        if ($navbar.className.indexOf('in') < 0) {
          $collapse.style.height = "0px"
        }
      }, 400)
    } else {
      // OPEN
      $collapse.style.height = "auto"
      $navbar.className += " in";
    }
  }
</script>


		<!-- Post Header (contains intro-header、signature、wordcount、busuanzi、waveoverlay) -->
		<!-- Modified by Yu-Hsuan Yen -->
<!-- Post Header -->

  <style type="text/css">
    .body--light {
      /* intro-header */
      --intro-header-background-image-url-home: url('/img/header_img/home_bg1.jpg');
      --intro-header-background-image-url-post: url('/img/header_img/lml_bg.jpg');
      --intro-header-background-image-url-page: url('//img/header_img/lml_bg.jpg');
    }
    .body--dark {
      --intro-header-background-image-url-home: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), url('/img/header_img/home_bg1.jpg');
      --intro-header-background-image-url-post: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), url('/img/header_img/lml_bg.jpg');
      --intro-header-background-image-url-page: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), url('//img/header_img/lml_bg.jpg');
    }

    header.intro-header {
       /*post*/
        background-image: var(--intro-header-background-image-url-post);
        /* background-image: url('/img/header_img/lml_bg.jpg'); */
      
    }

    
      #signature {/*signature*/
        background-image: url('/img/signature/signature.png');
      }
    
  </style>





<header class="intro-header">
  <!-- Signature -->
  <div id="signature">
    <div class="container">
      <div class="row">
        <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
          
          <div class="post-heading">
            <div class="tags">
              
              <a class="tag" href="/tags/#python" title="python">python</a>
              
              <a class="tag" href="/tags/#基础" title="基础">基础</a>
              
            </div>
            <h1>python基础 &gt; 详解Python序列结构</h1>
            <h2 class="subheading"></h2>
            <span class="meta">
              Posted by zhuang on
              2020-09-28
            </span>


            
            <!-- WordCount start -->
            <div class="blank_box"></div>
            <span class="meta">
              Estimated Reading Time <span class="post-count">14</span> Minutes
            </span>
            <div class="blank_box"></div>
            <span class="meta">
              Words <span class="post-count">3.6k</span> In Total
            </span>
            <div class="blank_box"></div>
            <!-- WordCount end -->
            
            
            <!-- 不蒜子统计 start -->
            <span class="meta" id="busuanzi_container_page_pv">
              Viewed <span id="busuanzi_value_page_pv"><i class="fa fa-spinner fa-spin"></i></span> Times
            </span>
            <!-- 不蒜子统计 end -->
            


          </div>
          
        </div>
      </div>
    </div>
  </div>

  
  <!-- waveoverlay start -->
  <div class="preview-overlay">
    <svg class="preview-waves" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto">
      <defs>
        <path id="gentle-wave" d="M-160 44c30 0 58-18 88-18s 58 18 88 18 58-18 88-18 58 18 88 18 v44h-352z"></path>
      </defs>
      <g class="preview-parallax">
        <use xlink:href="#gentle-wave" x="48" y="0" fill=var(--gentle-wave1)></use>
        <use xlink:href="#gentle-wave" x="48" y="3" fill=var(--gentle-wave2)></use>
        <use xlink:href="#gentle-wave" x="48" y="5" fill=var(--gentle-wave3)></use>
        <use xlink:href="#gentle-wave" x="48" y="7" fill=var(--gentle-wave)></use>
      </g>
    </svg>
  </div>
  <!-- waveoverlay end -->
  

</header>



		<!-- Main Content (Post contains
	Pager、
	tip、
	socialshare、
	gitalk、gitment、disqus-comment、
	Catalog、
	Sidebar、
	Featured-Tags、
	Friends Blog、
	anchorjs、
	) -->
		<!-- Modify by Yu-Hsuan Yen -->
<!-- Post Content -->
<article>
  <div class="container">
    <div class="row">
      <!-- Post Container -->
      <div class="col-lg-8 col-lg-offset-1 col-md-10 col-md-offset-1 post-container">

        <p>Python序列可以分为：</p>
<ul>
<li>无序序列<ul>
<li>字典</li>
<li>集合</li>
</ul>
</li>
<li>有序序列<ul>
<li>列表</li>
<li>元组</li>
<li>字符串</li>
</ul>
</li>
</ul>
<p>Python序列又可以分为：</p>
<ul>
<li>可变序列<ul>
<li>列表</li>
<li>字典</li>
<li>集合</li>
</ul>
</li>
<li>不可变序列<ul>
<li>元组</li>
<li>字符串</li>
</ul>
</li>
</ul>
<p>列表、元组、字符串等有序序列以及range对象均支持<code>双向索引</code>，可以使用<code>负整数</code>作为索引访问元素如a[-1]取列表的最后一个元素。</p>
<h3 id="列表、元组、字典、集合比较"><a href="#列表、元组、字典、集合比较" class="headerlink" title="列表、元组、字典、集合比较"></a>列表、元组、字典、集合比较</h3><div class="table-container">
<table>
<thead>
<tr>
<th>比较项</th>
<th>列表</th>
<th>元组</th>
<th>字典</th>
<th>集合</th>
</tr>
</thead>
<tbody>
<tr>
<td>类型名称</td>
<td>list</td>
<td>tuple</td>
<td>dict</td>
<td>set</td>
</tr>
<tr>
<td>定界符</td>
<td>[]</td>
<td>（）</td>
<td>{}</td>
<td>{}</td>
</tr>
<tr>
<td>是否可变</td>
<td>是</td>
<td>否</td>
<td>是</td>
<td>是</td>
</tr>
<tr>
<td>是否有序</td>
<td>是</td>
<td>是</td>
<td>否</td>
<td>否</td>
</tr>
<tr>
<td>是否支持下标</td>
<td>是</td>
<td>是</td>
<td>是（键）</td>
<td>否</td>
</tr>
<tr>
<td>对元素形式的要求</td>
<td>无</td>
<td>无</td>
<td>键值对</td>
<td>必须可哈希</td>
</tr>
<tr>
<td>对元素值的要求</td>
<td>无</td>
<td>无</td>
<td>键必须可哈希</td>
<td>必须可哈希</td>
</tr>
<tr>
<td>元素是否可重复</td>
<td>是</td>
<td>是</td>
<td>键不可重复，值可重复</td>
<td>否</td>
</tr>
<tr>
<td>元素查找速度</td>
<td>非常慢</td>
<td>很慢</td>
<td>非常快</td>
<td>非常快</td>
</tr>
<tr>
<td>新增和删除元素速度</td>
<td>尾部操作快，其他慢</td>
<td>不允许</td>
<td>快</td>
<td>快</td>
</tr>
</tbody>
</table>
</div>
<hr>
<h3 id="一、列表"><a href="#一、列表" class="headerlink" title="一、列表"></a>一、列表</h3><ul>
<li>list是包含若干个元素的有序连续内存空间，动态进行内存的扩展或收缩</li>
<li>尽量从列表尾部进行元素的追加与删除操作。</li>
<li>同一列表中元素的数据类型可以各不相同，包含基本类型和对象。只有一对方括号而没有任何元素则表示空列表。</li>
<li>Python采用基于值的自动内存管理模式，变量并不直接存储值，而是存储值的引用或内存地址，列表中的元素也是值的引用。</li>
<li>列表负担大、开销大，应避免过多使用列表。</li>
</ul>
<h4 id="1-列表的创建和删除"><a href="#1-列表的创建和删除" class="headerlink" title="1. 列表的创建和删除"></a>1. 列表的创建和删除</h4><p>使用<code>=</code>直接将一个列表赋值给变量即可创建表对象，也可以使用<code>list()</code>函数把迭代对象转换为列表。</p>
<blockquote>
<p>把字典转为列表时默认是将字典的“键”转为列表，如果想把字典元素转为列表，需使用字典对象的items()方法，要把字典的“值”转为列表可以使用values()</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">list_item = [<span class="string">&#x27;a&#x27;</span>,<span class="string">&#x27;b&#x27;</span>,<span class="string">&#x27;c&#x27;</span>,<span class="string">&#x27;d&#x27;</span>]</span><br><span class="line">list_item = []    <span class="comment">#空列表</span></span><br><span class="line">list_item = <span class="built_in">list</span>() <span class="comment">#空列表</span></span><br><span class="line"></span><br><span class="line">list_item_tuple = <span class="built_in">list</span>((<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>))   <span class="comment">#将元组转为列表</span></span><br><span class="line"><span class="comment">#[2, 3, 4, 5, 6]</span></span><br><span class="line"></span><br><span class="line">list_item_range = <span class="built_in">list</span>(<span class="built_in">range</span>(<span class="number">1</span>,<span class="number">21</span>,<span class="number">2</span>)) <span class="comment">#将range对象转为列表</span></span><br><span class="line"><span class="comment">#[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]</span></span><br><span class="line"></span><br><span class="line">list_item_str = <span class="built_in">list</span>(<span class="string">&#x27;hello world&#x27;</span>)   <span class="comment">#将字符串转为列表</span></span><br><span class="line"><span class="comment">#[&#x27;h&#x27;, &#x27;e&#x27;, &#x27;l&#x27;, &#x27;l&#x27;, &#x27;o&#x27;, &#x27; &#x27;, &#x27;w&#x27;, &#x27;o&#x27;, &#x27;r&#x27;, &#x27;l&#x27;, &#x27;d&#x27;]</span></span><br><span class="line"></span><br><span class="line">list_item_dict_index = <span class="built_in">list</span>(&#123;<span class="string">&#x27;a&#x27;</span>:<span class="number">1</span>,<span class="string">&#x27;b&#x27;</span>:<span class="number">2</span>,<span class="string">&#x27;c&#x27;</span>:<span class="number">2</span>&#125;)  <span class="comment">#将字典的键转为列表</span></span><br><span class="line"><span class="comment">#[&#x27;a&#x27;, &#x27;b&#x27;, &#x27;c&#x27;]</span></span><br><span class="line"></span><br><span class="line">list_item_dict = <span class="built_in">list</span>(&#123;<span class="string">&#x27;a&#x27;</span>:<span class="number">1</span>,<span class="string">&#x27;b&#x27;</span>:<span class="number">2</span>,<span class="string">&#x27;c&#x27;</span>:<span class="number">2</span>&#125;.items())  <span class="comment">#将字典的元素转为列表</span></span><br><span class="line"><span class="comment">#[(&#x27;a&#x27;, 1), (&#x27;b&#x27;, 2), (&#x27;c&#x27;, 2)]</span></span><br><span class="line"></span><br><span class="line">list_item_dict_value = <span class="built_in">list</span>(&#123;<span class="string">&#x27;a&#x27;</span>:<span class="number">1</span>,<span class="string">&#x27;b&#x27;</span>:<span class="number">2</span>,<span class="string">&#x27;c&#x27;</span>:<span class="number">2</span>&#125;.values())  <span class="comment">#将字典的键转为列表</span></span><br><span class="line"><span class="comment">#[1, 2, 2]</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>使用<code>del</code>来删除列表</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">del</span> list_item_dict_value</span><br><span class="line"><span class="built_in">print</span>(list_item_dict_value)</span><br><span class="line"><span class="comment">#NameError: name &#x27;list_item_dict_value&#x27; is not defined</span></span><br></pre></td></tr></table></figure>
<h4 id="2-列表元素访问"><a href="#2-列表元素访问" class="headerlink" title="2.列表元素访问"></a>2.列表元素访问</h4><p>使用整数作为下标来访问，还支持负整数作为下标。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">print</span>(list_item_tuple[<span class="number">0</span>])    <span class="comment">#2</span></span><br><span class="line"><span class="built_in">print</span>(list_item_tuple[-<span class="number">1</span>])   <span class="comment">#6</span></span><br></pre></td></tr></table></figure>
<h4 id="3-列表常用方法"><a href="#3-列表常用方法" class="headerlink" title="3. 列表常用方法"></a>3. 列表常用方法</h4><h5 id="3-1-添加元素方法-append-、insert-、extend"><a href="#3-1-添加元素方法-append-、insert-、extend" class="headerlink" title="3.1 添加元素方法 append()、insert()、extend()"></a>3.1 添加元素方法 append()、insert()、extend()</h5><ul>
<li>append()：用于向列表尾部追加一个元素</li>
<li>insert()：用于指定位置插入一个元素</li>
<li>extend()：用于将另一个列表追加至当前列表的尾部</li>
</ul>
<p>3个方法属于原地操作，不影响列表对象在内存中的起始地址</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">list_item = <span class="built_in">list</span>((<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>))</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">id</span>(list_item))    <span class="comment">#查看对象的内存地址  2503019068608</span></span><br><span class="line"></span><br><span class="line">list_item.append(<span class="number">5</span>)   </span><br><span class="line">list_item.insert(<span class="number">0</span>,<span class="number">0</span>)</span><br><span class="line">list_item.extend([<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>])</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(list_item)   <span class="comment">#[0, 1, 2, 3, 4, 5, 6, 7, 8]</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">id</span>(list_item))    <span class="comment">#查看对象的内存地址  2503019068608</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>使用insert()在指定位置插入元素时效率低</p>
</blockquote>
<h5 id="3-2-删除元素方法-pop-、remove-、clear"><a href="#3-2-删除元素方法-pop-、remove-、clear" class="headerlink" title="3.2 删除元素方法 pop()、remove()、clear()"></a>3.2 删除元素方法 pop()、remove()、clear()</h5><ul>
<li>pop()：用于删除并返回指定位置(默认最后一个)，指定位置不合法抛出异常</li>
<li>remove()：用于删除列表中第一个值与指定值相等的元素，不存在该元素抛出异常</li>
<li>clear()：用于清空列表中所有元素</li>
<li>del命令：也可以删除指定位置的元素</li>
</ul>
<p>3个方法属于原地操作，不影响列表对象在内存中的起始地址</p>
<blockquote>
<p>列表具有内存自动收缩和扩张功能，在列表中间插入或删除元素时，效率低还会影响后面所有元素的索引</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">list_item = <span class="built_in">list</span>((<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>))</span><br><span class="line"></span><br><span class="line">list_end = list_item.pop();     <span class="comment">#弹出并返回尾部元素</span></span><br><span class="line"><span class="built_in">print</span>(list_end)    <span class="comment">#8</span></span><br><span class="line"><span class="built_in">print</span>(list_item)   <span class="comment">#[1, 2, 3, 4, 5, 5, 6, 7]</span></span><br><span class="line"></span><br><span class="line">item = list_item.pop(<span class="number">0</span>)   <span class="comment">#弹出并返回指定位置元素</span></span><br><span class="line"><span class="built_in">print</span>(item)       <span class="comment">#1</span></span><br><span class="line"><span class="built_in">print</span>(list_item)  <span class="comment">#[2, 3, 4, 5, 5, 6, 7]</span></span><br><span class="line"></span><br><span class="line">list_item.remove(<span class="number">5</span>)    <span class="comment">#删除首个值为5的元素</span></span><br><span class="line"><span class="built_in">print</span>(list_item)       <span class="comment">#[2, 3, 4, 5, 6, 7]</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">del</span> list_item[<span class="number">3</span>]      <span class="comment">#使用del命令删除指定元素</span></span><br><span class="line"><span class="built_in">print</span>(list_item)      <span class="comment">#[2, 3, 4, 6, 7]</span></span><br><span class="line"></span><br><span class="line">list_item.clear()    <span class="comment">#删除所有元素</span></span><br><span class="line"><span class="built_in">print</span>(list_item)     <span class="comment">#[]</span></span><br></pre></td></tr></table></figure>
<h5 id="3-3-统计元素方法-count-、index"><a href="#3-3-统计元素方法-count-、index" class="headerlink" title="3.3 统计元素方法 count()、index()"></a>3.3 统计元素方法 count()、index()</h5><ul>
<li>count()：用于返回列表中指定元素出现的次数，不存在则返回0</li>
<li>index()：用于返回指定元素在列表中首次出现的位置，不存在则抛出异常</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">list_item = <span class="built_in">list</span>((<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">5</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">8</span>))</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(list_item.count(<span class="number">3</span>))    <span class="comment">#1</span></span><br><span class="line"><span class="built_in">print</span>(list_item.count(<span class="number">5</span>))   <span class="comment">#3</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(list_item.index(<span class="number">5</span>))    <span class="comment">#4</span></span><br><span class="line"><span class="built_in">print</span>(list_item.index(<span class="number">9</span>))   <span class="comment">#9 is not in list</span></span><br></pre></td></tr></table></figure>
<h5 id="3-4-排序方法-sort-、reverse"><a href="#3-4-排序方法-sort-、reverse" class="headerlink" title="3.4 排序方法 sort()、reverse()"></a>3.4 排序方法 sort()、reverse()</h5><h5 id="3-5-浅拷贝方法-copy"><a href="#3-5-浅拷贝方法-copy" class="headerlink" title="3.5 浅拷贝方法 copy()"></a>3.5 浅拷贝方法 copy()</h5><h4 id="4-列表支持的运算符"><a href="#4-列表支持的运算符" class="headerlink" title="4. 列表支持的运算符"></a>4. 列表支持的运算符</h4><h5 id="4-1-加法运算符"><a href="#4-1-加法运算符" class="headerlink" title="4.1 加法运算符"></a>4.1 加法运算符</h5><p><code>+</code>可以实现列表增加元素的目的，不属于原地操作，返回新的列表，涉及大量元素复制，效率非常低</p>
<p>使用<code>+=</code>复合赋值运算符实现列表追加元素属于原地操作，与append()方法一样高效。</p>
<h5 id="4-2-乘法运算符"><a href="#4-2-乘法运算符" class="headerlink" title="4.2 乘法运算符"></a>4.2 乘法运算符</h5><p><code>*</code>可以用于列表和整数相乘，表示序列重复，返回新列表。<code>*=</code>也可以用于列表元素重复属于原地操作。</p>
<h5 id="4-3-in运算符"><a href="#4-3-in运算符" class="headerlink" title="4.3 in运算符"></a>4.3 in运算符</h5><p><code>in</code>可用于测试列表中是否包含某个元素。</p>
<h4 id="5-内置函数对列表的操作"><a href="#5-内置函数对列表的操作" class="headerlink" title="5. 内置函数对列表的操作"></a>5. 内置函数对列表的操作</h4><ul>
<li>max()、min()：函数返回列表中所有元素的最大值、最小值</li>
<li>sum()：用于返回列表中所有元素之和</li>
<li>len()：用于返回列表中元素的个数</li>
<li>zip()：用于将多个列表中元素重新组合为元组并返回包含这些元组的zip对象</li>
<li>enumerate()：返回包含若干下标和值的迭代对象</li>
<li>map()：把函数映射到列表上的每个元素</li>
<li>filter()：根据指定函数的返回值对列表元素进行过滤</li>
<li>all()：用来测试列表中是否所有元素都等价于True</li>
<li>any()：用来测试列表中是否有等价于True的元素</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">item = <span class="built_in">list</span>(<span class="built_in">range</span>(<span class="number">10</span>));</span><br><span class="line">list_item = <span class="built_in">list</span>(<span class="built_in">zip</span>(item,[<span class="number">2</span>] * <span class="number">10</span>))   <span class="comment"># 多列表元素重新组合</span></span><br><span class="line"><span class="built_in">print</span>(list_item)    <span class="comment">#[(0, 2), (1, 2), (2, 2), (3, 2), (4, 2), (5, 2), (6, 2), (7, 2), (8, 2), (9, 2)]</span></span><br><span class="line"></span><br><span class="line">list_item = <span class="built_in">list</span>(<span class="built_in">zip</span>(<span class="built_in">range</span>(<span class="number">1</span>,<span class="number">5</span>)))      <span class="comment"># zip()函数也可以用于一个序列或迭代对象</span></span><br><span class="line"><span class="built_in">print</span>(list_item)    <span class="comment">#[(1,), (2,), (3,), (4,)]</span></span><br><span class="line"></span><br><span class="line">list_item = <span class="built_in">list</span>(<span class="built_in">zip</span>([<span class="string">&#x27;a&#x27;</span>,<span class="string">&#x27;b&#x27;</span>,<span class="string">&#x27;c&#x27;</span>,<span class="string">&#x27;d&#x27;</span>],[<span class="number">1</span>,<span class="number">2</span>]))   <span class="comment">#如果两个列表不等长，则以短的为准</span></span><br><span class="line"><span class="built_in">print</span>(list_item)    <span class="comment">#[(&#x27;a&#x27;, 1), (&#x27;b&#x27;, 2)]</span></span><br><span class="line"></span><br><span class="line">enum_item = <span class="built_in">enumerate</span>(item) <span class="comment">#枚举类表元素，返回enumerate对象</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">type</span>(enum_item))   <span class="comment">#&lt;class &#x27;enumerate&#x27;&gt;</span></span><br><span class="line"></span><br><span class="line">list_item = <span class="built_in">list</span>(enum_item)  <span class="comment">#enumerate对象可以转化为列表、元组、集合</span></span><br><span class="line"><span class="built_in">print</span>(list_item)   <span class="comment">#[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]</span></span><br></pre></td></tr></table></figure>
<h4 id="6-列表推导式"><a href="#6-列表推导式" class="headerlink" title="6. 列表推导式"></a>6. 列表推导式</h4><p>列表推导式也称为列表解析式，可以使用非常简洁的方式对列表或其他可迭代对象的元素进行遍历，过滤或再次计算。</p>
<p>列表推导式的语法为:</p>
<blockquote>
<p>[expression for expr1 in sequence1 if condition 1</p>
<p>​                      for expr2 in sequence1 if condition 2</p>
<p>​                      for expr3 in sequence1 if condition 3</p>
<p>​                    ….</p>
<p>]</p>
</blockquote>
<p>列表推导式在逻辑上等价于一个循环语句</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">listItem = [<span class="string">&#x27; banana &#x27;</span>, <span class="string">&#x27;  loganberry  &#x27;</span>, <span class="string">&#x27;passion fruit &#x27;</span>]</span><br><span class="line">alist = [item.strip() <span class="keyword">for</span> item <span class="keyword">in</span> listItem]</span><br><span class="line"></span><br><span class="line"><span class="comment">#等价于</span></span><br><span class="line">alist = []</span><br><span class="line"><span class="keyword">for</span> item <span class="keyword">in</span> listItem:</span><br><span class="line">    alist.append(item.strip())</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">#等价于</span></span><br><span class="line">alist = <span class="built_in">list</span>(<span class="built_in">map</span>(<span class="keyword">lambda</span> x: x.strip(),listItem))</span><br><span class="line"></span><br><span class="line"><span class="comment">#等价于</span></span><br><span class="line">alist = <span class="built_in">list</span>(<span class="built_in">map</span>(<span class="built_in">str</span>.strip,listItem))</span><br></pre></td></tr></table></figure>
<h5 id="6-1-实现嵌套列表的平铺"><a href="#6-1-实现嵌套列表的平铺" class="headerlink" title="6.1 实现嵌套列表的平铺"></a>6.1 实现嵌套列表的平铺</h5><ul>
<li>一层嵌套列表的平铺</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">listItem = [[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>], [<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>], [<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>]]</span><br><span class="line">aList = <span class="built_in">list</span>(value <span class="keyword">for</span> item <span class="keyword">in</span> listItem <span class="keyword">for</span> value <span class="keyword">in</span> item)</span><br><span class="line"><span class="built_in">print</span>(aList)   <span class="comment">#[1, 2, 3, 4, 5, 6, 7, 8, 9]</span></span><br></pre></td></tr></table></figure>
<ul>
<li>多级嵌套或者不同子列表嵌套深度不同</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">listItem = [[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>], [<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,[<span class="string">&#x27;a&#x27;</span>,<span class="string">&#x27;b&#x27;</span>,[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,[<span class="string">&#x27;a&#x27;</span>]]]], [<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>]]</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">flatList</span>(<span class="params">lst</span>):</span></span><br><span class="line">    result = []</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">nested</span>(<span class="params">lst</span>):</span></span><br><span class="line">        <span class="keyword">for</span> item <span class="keyword">in</span> lst:</span><br><span class="line">            <span class="keyword">if</span> <span class="built_in">isinstance</span>(item,<span class="built_in">list</span>):</span><br><span class="line">                nested(item)</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                result.append(item)</span><br><span class="line">    nested(lst)</span><br><span class="line">    <span class="keyword">return</span> result</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(flatList(listItem))   <span class="comment">#[1, 2, 3, 4, 5, 6, &#x27;a&#x27;, &#x27;b&#x27;, 1, 2, 3, &#x27;a&#x27;, 7, 8, 9]</span></span><br></pre></td></tr></table></figure>
<h5 id="6-2-过滤不符合条件的元素"><a href="#6-2-过滤不符合条件的元素" class="headerlink" title="6.2 过滤不符合条件的元素"></a>6.2 过滤不符合条件的元素</h5><p>使用<code>if</code>子句对列表中的元素进行筛选</p>
<ul>
<li>筛选当前文件夹下所有python源文件</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> os</span><br><span class="line">alist = <span class="built_in">list</span>(filename <span class="keyword">for</span> filename <span class="keyword">in</span> os.listdir(<span class="string">&#x27;.&#x27;</span>) <span class="keyword">if</span> filename.endswith((<span class="string">&#x27;.py&#x27;</span>,<span class="string">&#x27;.pyw&#x27;</span>)))</span><br></pre></td></tr></table></figure>
<ul>
<li>选择符合条件的元素</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">listitem = [-<span class="number">1</span>,-<span class="number">5</span>,<span class="number">0</span>,-<span class="number">7</span>,<span class="number">4</span>,<span class="number">2</span>,-<span class="number">9</span>]</span><br><span class="line"></span><br><span class="line">alist = <span class="built_in">list</span>(item <span class="keyword">for</span> item <span class="keyword">in</span> listitem <span class="keyword">if</span> item &gt; <span class="number">0</span>)</span><br><span class="line"><span class="built_in">print</span>(alist)  <span class="comment">#[4, 2]</span></span><br></pre></td></tr></table></figure>
<h4 id="7-切片操作"><a href="#7-切片操作" class="headerlink" title="7. 切片操作"></a>7. 切片操作</h4><p>切片适用于列表、元组、字符串、range对象。切片不仅可以来截取列表中的任何部分返回得到一个新列表，也可以通过切片来修改和删除列表中部分元素，甚至可以通过切片操作为列表对象增加元素。</p>
<p>在形式<code>[start:end:step]</code></p>
<ul>
<li>第一个数字start：表示切片开始的位置，默认为0</li>
<li>第二个数字end：表示切片截止（但不包含）的位置，默认为列表长度</li>
<li>第三个数字step：表示切片的步长(默认为1)，0可以省略，为列表长度可省略。当step为负整数时，表示反向切片，start应该在end的右侧才行。</li>
</ul>
<hr>
<h3 id="二、元组：轻量级列表"><a href="#二、元组：轻量级列表" class="headerlink" title="二、元组：轻量级列表"></a>二、元组：轻量级列表</h3><h4 id="1-元组创建与元素访问"><a href="#1-元组创建与元素访问" class="headerlink" title="1. 元组创建与元素访问"></a>1. 元组创建与元素访问</h4><p>元组的所有元素放在一对圆括号中，用逗号分开，</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">x = (<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>)</span><br><span class="line">x = <span class="built_in">tuple</span>(<span class="built_in">range</span>(<span class="number">5</span>))</span><br></pre></td></tr></table></figure>
<ul>
<li>元组支持下标访问</li>
<li>元组支持双向索引</li>
<li>元组不可改变</li>
<li>如果元组只有一个元素则必须在最后加一个逗号</li>
</ul>
<h4 id="2-元组与列表的异同点"><a href="#2-元组与列表的异同点" class="headerlink" title="2. 元组与列表的异同点"></a>2. 元组与列表的异同点</h4><ul>
<li>列表和元组都属于有序序列，都支持使用双向索引访问其中的元素</li>
<li>元组属于不可变序列，不可以直接修改元组中的元素的值，也无法为元组增加和删除</li>
<li>python实现对元组做了大量优化，访问速度比列表更快</li>
<li>列表则永远都不能当做字典键使用，也不能作为集合中的元素</li>
</ul>
<h4 id="3-生成器推导式"><a href="#3-生成器推导式" class="headerlink" title="3. 生成器推导式"></a>3. 生成器推导式</h4><p>生成器推导式使用圆括号作为定界符，而不是列表推导式所使用的方括号。</p>
<blockquote>
<p>与列表推导式最大的不同是：生成器推导式的结果是一个生成器对象</p>
</blockquote>
<p><strong>没有任何方法可以再次访问已访问过的元素，也不支持使用下标访问其中的元素</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">g = (i <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">10</span>))</span><br><span class="line"><span class="built_in">print</span>(g.__next__())</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">next</span>(g))</span><br></pre></td></tr></table></figure>
<hr>
<h3 id="三、字典：放映对应关系"><a href="#三、字典：放映对应关系" class="headerlink" title="三、字典：放映对应关系"></a>三、字典：放映对应关系</h3><p>字典（dict）是包含若干键值对元素的无序可变序列，表示一种映射或对应关系，定界符为大括号”{}”中。</p>
<ul>
<li>键：是不可变数据，可哈希数据，不允许重复，键可以重复</li>
<li>字典在内部维护的哈希表使检索操作快</li>
</ul>
<h4 id="1-创建与删除"><a href="#1-创建与删除" class="headerlink" title="1. 创建与删除"></a>1. 创建与删除</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#1. 使用赋值运算符 =</span></span><br><span class="line">adict = &#123;<span class="string">&#x27;db&#x27;</span>:<span class="string">&#x27;db.diveintopython2.org&#x27;</span>,<span class="string">&#x27;database&#x27;</span>:<span class="string">&#x27;mysql&#x27;</span>&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">#2. 使用内置类dict</span></span><br><span class="line">keys = &#123;<span class="string">&#x27;a&#x27;</span>,<span class="string">&#x27;b&#x27;</span>,<span class="string">&#x27;c&#x27;</span>&#125;</span><br><span class="line">valuses = &#123;<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>&#125;</span><br><span class="line">bdict = <span class="built_in">dict</span>(<span class="built_in">zip</span>(keys,valuses))</span><br><span class="line"></span><br><span class="line">cdict = <span class="built_in">dict</span>(name = <span class="string">&#x27;python&#x27;</span>,ver = <span class="string">&#x27;3&#x27;</span>)</span><br></pre></td></tr></table></figure>
<h4 id="2-元素的访问"><a href="#2-元素的访问" class="headerlink" title="2. 元素的访问"></a>2. 元素的访问</h4><ul>
<li>get()</li>
<li>setdefault()</li>
</ul>
<h4 id="3-添加、修改与删除"><a href="#3-添加、修改与删除" class="headerlink" title="3. 添加、修改与删除"></a>3. 添加、修改与删除</h4><p>当以指定”键”为下标为字典元素赋值时，</p>
<ol>
<li>若该键存在，则表示修改键对应的值</li>
<li>如该键不存在，则表示添加新的元素</li>
</ol>
<ul>
<li>update()：将另一个字典全部添加到当前字典对象中</li>
<li>setdefault()：也可以用来添加元素</li>
<li>pop()、popitem()方法弹出并删除指定元素</li>
</ul>
<hr>
<h3 id="四、集合：不允许重复"><a href="#四、集合：不允许重复" class="headerlink" title="四、集合：不允许重复"></a>四、集合：不允许重复</h3><p>集合中只能包含数字、字符串、元组等不可变类型（或者说可哈希）的数据、而不能包含列表、字典、集合等可变类型的数据。</p>
<blockquote>
<p>内置函数 hash() 计算对象的哈希值，无法计算哈希值的对象不能作为集合的元素</p>
</blockquote>
<h4 id="1-集合对象的创建与删除"><a href="#1-集合对象的创建与删除" class="headerlink" title="1. 集合对象的创建与删除"></a>1. 集合对象的创建与删除</h4><ul>
<li>直接将集合赋值给变量</li>
<li>使用set()函数将列表、元组、字符串、range对象等迭代对象转为集合</li>
<li>支持集合推导式来生成集合</li>
</ul>
<h4 id="2-集合操作与运算"><a href="#2-集合操作与运算" class="headerlink" title="2. 集合操作与运算"></a>2. 集合操作与运算</h4><h5 id="2-1-增加与删除集合元素"><a href="#2-1-增加与删除集合元素" class="headerlink" title="2.1 增加与删除集合元素"></a>2.1 增加与删除集合元素</h5><ul>
<li>add()：增加新元素，存在忽略，不会抛出异常</li>
<li><p>update()：合并另一个集合到当前集合，并自动去重</p>
</li>
<li><p>pop()：随机删除并返回集合中的一个元素，空则抛出异常</p>
</li>
<li>remove()：删除集合中的元素</li>
<li>discard()：从集合中删除一个特定元素</li>
<li>clear()：清空集合</li>
</ul>
<h5 id="2-2-集合运算"><a href="#2-2-集合运算" class="headerlink" title="2.2 集合运算"></a>2.2 集合运算</h5><p>内置函数也适用于集合，支持交、并、差集等运算</p>
<p>关系运算符&gt; 、&gt;=、&lt;、&lt;= 作用于集合时表示集合之间包含关系，而不是比较集合中元素的大小关系。</p>
<h4 id="3-集合-应用案例"><a href="#3-集合-应用案例" class="headerlink" title="3.集合 应用案例"></a>3.集合 应用案例</h4><ul>
<li>关键字in 作用于字典和集合时比作用于列表要快得多。</li>
<li>集合中元素不允许重复，添加元素时如果已经存在重复元素则自动忽略</li>
</ul>
<p>假设已有若干用户名字及其喜欢的电影清单，现有某用户，已看过并喜欢一些电影，现在想找个新电影看看，又不知道看什么好。根据已有数据，查找与该用户爱好最相似的用户，也就是看过并喜欢的电影与该用户最接近的用户，然后从那个用户喜欢的电影中选取一个当前用户还没看过的电影，然后推荐。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> random <span class="keyword">import</span> randrange</span><br><span class="line"></span><br><span class="line">data = &#123;<span class="string">&#x27;user&#x27;</span> + <span class="built_in">str</span>(i) : &#123;<span class="string">&#x27;film&#x27;</span> + <span class="built_in">str</span>(randrange(<span class="number">1</span>,<span class="number">10</span>)) <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(randrange(<span class="number">15</span>))&#125; <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">10</span>)&#125;</span><br><span class="line"></span><br><span class="line">user = &#123;<span class="string">&#x27;film1&#x27;</span>, <span class="string">&#x27;film2&#x27;</span>, <span class="string">&#x27;film3&#x27;</span>&#125;</span><br><span class="line">similarUser, films = <span class="built_in">max</span>(data.items(), key = <span class="keyword">lambda</span> item:<span class="built_in">len</span>(item[<span class="number">1</span>] &amp; user))</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;历史数据：&#x27;</span>)</span><br><span class="line"><span class="keyword">for</span> u, f <span class="keyword">in</span> data.items():</span><br><span class="line">    <span class="built_in">print</span>(u,f,sep=<span class="string">&#x27;:&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;和您最相似的用户是：&#x27;</span>,similarUser)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;他最喜欢看的电影是：&#x27;</span>,films)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;他看过的电影中您还没看过的有：&#x27;</span>,films - user)</span><br></pre></td></tr></table></figure>
<p><img src="image-20201013201840530.png" alt="image-20201013201840530"></p>


        <hr>
        <!-- Pager -->
        <ul class="pager">
          
          <li class="previous">
            <a href="/cn/python/程序控制结构/" data-toggle="tooltip" data-placement="top" title="python基础 > 程序控制结构">&larr; Previous Post</a>
          </li>
          
          
          <li class="next">
            <a href="/cn/python/运算符、表达式与内置对象/" data-toggle="tooltip" data-placement="top" title="python基础 > 运算符、表达式与内置对象">Next Post &rarr;</a>
          </li>
          
        </ul>

        
        <!-- tip start -->
        <!-- tip -->
<!-- tip start -->
<div class="tip">
  <p>
    
      如果您喜欢此博客或发现它对您有用，则欢迎对此发表评论。 也欢迎您共享此博客，以便更多人可以参与。 如果博客中使用的图像侵犯了您的版权，请与作者联系以将其删除。 谢谢 ！
    
  </p>
</div>
<!-- tip end -->

        <!-- tip end -->
        

        
        <hr>

        <!-- comments start -->
        <!-- 1. gitalk comment -->


<!-- 2. gitment comment -->


<!-- 3. disqus comment -->


        <!-- comments end -->
        <hr>

      </div>

      <!-- Catalog: Tabe of Content -->
      <!-- Table of Contents -->

    
      <aside id="sidebar">
        <div id="toc" class="toc-article">
        <strong class="toc-title">目录</strong>
        
          <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#%E5%88%97%E8%A1%A8%E3%80%81%E5%85%83%E7%BB%84%E3%80%81%E5%AD%97%E5%85%B8%E3%80%81%E9%9B%86%E5%90%88%E6%AF%94%E8%BE%83"><span class="toc-nav-number">1.</span> <span class="toc-nav-text">列表、元组、字典、集合比较</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#%E4%B8%80%E3%80%81%E5%88%97%E8%A1%A8"><span class="toc-nav-number">2.</span> <span class="toc-nav-text">一、列表</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#1-%E5%88%97%E8%A1%A8%E7%9A%84%E5%88%9B%E5%BB%BA%E5%92%8C%E5%88%A0%E9%99%A4"><span class="toc-nav-number">2.1.</span> <span class="toc-nav-text">1. 列表的创建和删除</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#2-%E5%88%97%E8%A1%A8%E5%85%83%E7%B4%A0%E8%AE%BF%E9%97%AE"><span class="toc-nav-number">2.2.</span> <span class="toc-nav-text">2.列表元素访问</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#3-%E5%88%97%E8%A1%A8%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95"><span class="toc-nav-number">2.3.</span> <span class="toc-nav-text">3. 列表常用方法</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-5"><a class="toc-nav-link" href="#3-1-%E6%B7%BB%E5%8A%A0%E5%85%83%E7%B4%A0%E6%96%B9%E6%B3%95-append-%E3%80%81insert-%E3%80%81extend"><span class="toc-nav-number">2.3.1.</span> <span class="toc-nav-text">3.1 添加元素方法 append()、insert()、extend()</span></a></li><li class="toc-nav-item toc-nav-level-5"><a class="toc-nav-link" href="#3-2-%E5%88%A0%E9%99%A4%E5%85%83%E7%B4%A0%E6%96%B9%E6%B3%95-pop-%E3%80%81remove-%E3%80%81clear"><span class="toc-nav-number">2.3.2.</span> <span class="toc-nav-text">3.2 删除元素方法 pop()、remove()、clear()</span></a></li><li class="toc-nav-item toc-nav-level-5"><a class="toc-nav-link" href="#3-3-%E7%BB%9F%E8%AE%A1%E5%85%83%E7%B4%A0%E6%96%B9%E6%B3%95-count-%E3%80%81index"><span class="toc-nav-number">2.3.3.</span> <span class="toc-nav-text">3.3 统计元素方法 count()、index()</span></a></li><li class="toc-nav-item toc-nav-level-5"><a class="toc-nav-link" href="#3-4-%E6%8E%92%E5%BA%8F%E6%96%B9%E6%B3%95-sort-%E3%80%81reverse"><span class="toc-nav-number">2.3.4.</span> <span class="toc-nav-text">3.4 排序方法 sort()、reverse()</span></a></li><li class="toc-nav-item toc-nav-level-5"><a class="toc-nav-link" href="#3-5-%E6%B5%85%E6%8B%B7%E8%B4%9D%E6%96%B9%E6%B3%95-copy"><span class="toc-nav-number">2.3.5.</span> <span class="toc-nav-text">3.5 浅拷贝方法 copy()</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#4-%E5%88%97%E8%A1%A8%E6%94%AF%E6%8C%81%E7%9A%84%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-nav-number">2.4.</span> <span class="toc-nav-text">4. 列表支持的运算符</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-5"><a class="toc-nav-link" href="#4-1-%E5%8A%A0%E6%B3%95%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-nav-number">2.4.1.</span> <span class="toc-nav-text">4.1 加法运算符</span></a></li><li class="toc-nav-item toc-nav-level-5"><a class="toc-nav-link" href="#4-2-%E4%B9%98%E6%B3%95%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-nav-number">2.4.2.</span> <span class="toc-nav-text">4.2 乘法运算符</span></a></li><li class="toc-nav-item toc-nav-level-5"><a class="toc-nav-link" href="#4-3-in%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-nav-number">2.4.3.</span> <span class="toc-nav-text">4.3 in运算符</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#5-%E5%86%85%E7%BD%AE%E5%87%BD%E6%95%B0%E5%AF%B9%E5%88%97%E8%A1%A8%E7%9A%84%E6%93%8D%E4%BD%9C"><span class="toc-nav-number">2.5.</span> <span class="toc-nav-text">5. 内置函数对列表的操作</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#6-%E5%88%97%E8%A1%A8%E6%8E%A8%E5%AF%BC%E5%BC%8F"><span class="toc-nav-number">2.6.</span> <span class="toc-nav-text">6. 列表推导式</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-5"><a class="toc-nav-link" href="#6-1-%E5%AE%9E%E7%8E%B0%E5%B5%8C%E5%A5%97%E5%88%97%E8%A1%A8%E7%9A%84%E5%B9%B3%E9%93%BA"><span class="toc-nav-number">2.6.1.</span> <span class="toc-nav-text">6.1 实现嵌套列表的平铺</span></a></li><li class="toc-nav-item toc-nav-level-5"><a class="toc-nav-link" href="#6-2-%E8%BF%87%E6%BB%A4%E4%B8%8D%E7%AC%A6%E5%90%88%E6%9D%A1%E4%BB%B6%E7%9A%84%E5%85%83%E7%B4%A0"><span class="toc-nav-number">2.6.2.</span> <span class="toc-nav-text">6.2 过滤不符合条件的元素</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#7-%E5%88%87%E7%89%87%E6%93%8D%E4%BD%9C"><span class="toc-nav-number">2.7.</span> <span class="toc-nav-text">7. 切片操作</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#%E4%BA%8C%E3%80%81%E5%85%83%E7%BB%84%EF%BC%9A%E8%BD%BB%E9%87%8F%E7%BA%A7%E5%88%97%E8%A1%A8"><span class="toc-nav-number">3.</span> <span class="toc-nav-text">二、元组：轻量级列表</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#1-%E5%85%83%E7%BB%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E5%85%83%E7%B4%A0%E8%AE%BF%E9%97%AE"><span class="toc-nav-number">3.1.</span> <span class="toc-nav-text">1. 元组创建与元素访问</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#2-%E5%85%83%E7%BB%84%E4%B8%8E%E5%88%97%E8%A1%A8%E7%9A%84%E5%BC%82%E5%90%8C%E7%82%B9"><span class="toc-nav-number">3.2.</span> <span class="toc-nav-text">2. 元组与列表的异同点</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#3-%E7%94%9F%E6%88%90%E5%99%A8%E6%8E%A8%E5%AF%BC%E5%BC%8F"><span class="toc-nav-number">3.3.</span> <span class="toc-nav-text">3. 生成器推导式</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#%E4%B8%89%E3%80%81%E5%AD%97%E5%85%B8%EF%BC%9A%E6%94%BE%E6%98%A0%E5%AF%B9%E5%BA%94%E5%85%B3%E7%B3%BB"><span class="toc-nav-number">4.</span> <span class="toc-nav-text">三、字典：放映对应关系</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#1-%E5%88%9B%E5%BB%BA%E4%B8%8E%E5%88%A0%E9%99%A4"><span class="toc-nav-number">4.1.</span> <span class="toc-nav-text">1. 创建与删除</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#2-%E5%85%83%E7%B4%A0%E7%9A%84%E8%AE%BF%E9%97%AE"><span class="toc-nav-number">4.2.</span> <span class="toc-nav-text">2. 元素的访问</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#3-%E6%B7%BB%E5%8A%A0%E3%80%81%E4%BF%AE%E6%94%B9%E4%B8%8E%E5%88%A0%E9%99%A4"><span class="toc-nav-number">4.3.</span> <span class="toc-nav-text">3. 添加、修改与删除</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#%E5%9B%9B%E3%80%81%E9%9B%86%E5%90%88%EF%BC%9A%E4%B8%8D%E5%85%81%E8%AE%B8%E9%87%8D%E5%A4%8D"><span class="toc-nav-number">5.</span> <span class="toc-nav-text">四、集合：不允许重复</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#1-%E9%9B%86%E5%90%88%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E5%88%A0%E9%99%A4"><span class="toc-nav-number">5.1.</span> <span class="toc-nav-text">1. 集合对象的创建与删除</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#2-%E9%9B%86%E5%90%88%E6%93%8D%E4%BD%9C%E4%B8%8E%E8%BF%90%E7%AE%97"><span class="toc-nav-number">5.2.</span> <span class="toc-nav-text">2. 集合操作与运算</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-5"><a class="toc-nav-link" href="#2-1-%E5%A2%9E%E5%8A%A0%E4%B8%8E%E5%88%A0%E9%99%A4%E9%9B%86%E5%90%88%E5%85%83%E7%B4%A0"><span class="toc-nav-number">5.2.1.</span> <span class="toc-nav-text">2.1 增加与删除集合元素</span></a></li><li class="toc-nav-item toc-nav-level-5"><a class="toc-nav-link" href="#2-2-%E9%9B%86%E5%90%88%E8%BF%90%E7%AE%97"><span class="toc-nav-number">5.2.2.</span> <span class="toc-nav-text">2.2 集合运算</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#3-%E9%9B%86%E5%90%88-%E5%BA%94%E7%94%A8%E6%A1%88%E4%BE%8B"><span class="toc-nav-number">5.3.</span> <span class="toc-nav-text">3.集合 应用案例</span></a></li></ol></li></ol>
        
        </div>
      </aside>
    



      <!-- Sidebar Container -->
      <div class="
                col-lg-8 col-lg-offset-1
                col-md-10 col-md-offset-1
                sidebar-container">

        <!-- Featured Tags -->
        
        <section>
          <!-- no hr -->
          <h5>
            <a href="/tags/">特色标签</a>
          </h5>
          <div class="tags">
            
            <a class="tag" href="/tags/#python" title="python">python</a>
            
            <a class="tag" href="/tags/#基础" title="基础">基础</a>
            
          </div>
        </section>
        

        <!-- Friends Blog -->
        
        <hr>
        <h5>链友</h5>
        <ul class="list-inline">

          
        </ul>
        
      </div>
    </div>
  </div>
</article>



<!-- anchorjs start -->
<!-- async load function -->
<!-- anchor-js, Doc:http://bryanbraun.github.io/anchorjs/ -->
<script type="text/javascript">
  // async load function
  function async (u, c) {
    var d = document,
      t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) {
      o.addEventListener('load', function(e) {
        c(null, e);
      }, false);
    }
    s.parentNode.insertBefore(o, s);
  };
</script>
<script type="text/javascript">
  //anchor-js, Doc:http://bryanbraun.github.io/anchorjs/
  async ("https://cdn.bootcss.com/anchor-js/1.1.1/anchor.min.js", function() {
    anchors.options = {
      visible: 'hover',
      placement: 'left',
      // icon: 'ℬ'
      icon: '❡'
    };
    anchors.add().remove('.intro-header h1').remove('.subheading').remove('.sidebar-container h5');
  });
</script>
<style>
  /* place left on bigger screen */
  @media all and (min-width: 800px) {
    .anchorjs-link {
      position: absolute;
      left: -0.75em;
      font-size: 1.1em;
      margin-top: -0.1em;
    }
  }
</style>

<!-- anchorjs end -->



		<!-- Footer (contains ThemeColor、viewer) -->
		<!-- Footer -->
<footer>
  <div class="container">
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        <ul class="list-inline text-center">
          

          

          

          

          

          

          

          

        </ul>
        <p class="copyright text-muted">
          Copyright &copy;
          zhuang
          2021
          <br>
          Theme by
          <a target="_blank" rel="noopener" href="http://beantech.org">BeanTech</a>
          <span style="display: inline-block; margin: 0 5px;">
            <i class="fa fa-heart"></i>
          </span>
          re-Ported by
          <a target="_blank" rel="noopener" href="https://v-vincen.life/">Live My Life</a>
        </p>
      </div>
    </div>
  </div>
</footer>

<a id="rocket" href="#top" class=""></a>


  <!-- jQuery -->
  <script type="text/javascript" src="/js/jquery.min.js"></script>
  <!-- Bootstrap Core JavaScript -->
  <script type="text/javascript" src="/js/bootstrap.min.js"></script>
  <!-- Custom Theme JavaScript -->
  <script type="text/javascript" src="/js/hux-blog.min.js"></script>
  <!-- catalog -->
  <script async="true" type="text/javascript" src="/js/catalog.js"></script>
  <!-- totop(rocket) -->
  <script async="true" type="text/javascript" src="/js/totop.js"></script>

  
    <!-- Busuanzi JavaScript -->
    <script async="async" src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
  

  
    <!-- Scroll start -->
    <script async="async" type="text/javascript" src="/js/scroll.js"></script>
    <!-- Scroll end -->
  

  

  

  
    <!-- ribbon -->
    <script type="text/javascript" src="/js/ribbonDynamic.js"></script>
  

  






  <!-- viewer start -->
  <!-- viewer start (Picture preview) -->
  
    <script async="async" type="text/javascript" src="/js/viewer/viewer.min.js"></script>
    <script async="async" type="text/javascript" src="/js/viewer/pic-viewer.js"></script>
  

  <!-- viewer end -->


<script>
  // async load function
  function async (u, c) {
    var d = document,
      t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) {
      o.addEventListener('load', function (e) {
        c(null, e);
      }, false);
    }
    s.parentNode.insertBefore(o, s);
  }

  // fastClick.js
  async ("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function () {
    var $nav = document.querySelector("nav");
    if ($nav)
      FastClick.attach($nav);
    }
  )
</script>

<!-- Because of the native support for backtick-style fenced code blocks right within the Markdown is landed in Github Pages, From V1.6, There is no need for Highlight.js, so Huxblog drops it officially. -
https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0 - https://help.github.com/articles/creating-and-highlighting-code-blocks/ -->
<!-- <script> async ("http://cdn.bootcss.com/highlight.js/8.6/highlight.min.js", function () { hljs.initHighlightingOnLoad(); }) </script> <link href="http://cdn.bootcss.com/highlight.js/8.6/styles/github.min.css" rel="stylesheet"> -->

<!-- jquery.tagcloud.js -->
<!-- <script> // only load tagcloud.js in tag.html if ($('#tag_cloud').length !== 0) { async ("http://yoursite-url/js/jquery.tagcloud.js", function () { $.fn.tagcloud.defaults = { // size: { start: 1, end: 1, unit: 'em' }, color: {
start: '#bbbbee', end: '#0085a1' } }; $('#tag_cloud a').tagcloud(); }) } </script> -->


		<!-- Search -->
		
		<div class="popup search-popup local-search-popup">
  <span class="popup-btn-close">
    ESC
  </span>
  <div class="container">
    <div class="row">
      <!-- <div class="col-md-9 col-md-offset-1"> -->
      <div class="col-lg-9 col-lg-offset-1 col-md-10 col-md-offset-1 local-search-content">

        <div class="local-search-header clearfix">

          <div class="local-search-input-wrapper">
            <span class="search-icon">
              <i class="fa fa-search fa-lg" style="margin: 25px 10px 25px 20px;"></i>
            </span>
            <input autocomplete="off" placeholder="搜索..." type="text" id="local-search-input">
          </div>
        </div>
        <div id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>


  
    <script src="/js/ziploader.js"></script>
  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.json";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    // monitor main search box;
    var onPopupClose = function (e) {
      $('.popup').fadeOut(300);
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $('.popup').fadeIn(300);
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }
    // get search zip version
    $.get('/searchVersion.json?t=' + (+new Date()), function (res) {
      if (localStorage.getItem('searchVersion') !== res) {
        localStorage.setItem('searchVersion', res);
        initSearchJson();
      }
    });

    function initSearchJson() {
      initLoad(['/search.flv'], {
        loadOptions: {
          success: function (obj) {
            localStorage.setItem('searchJson', obj['search.json'])
          },
          error: function (e) {
            return console.log(e)
          }
        },
        returnOptions: {
          'json': TYPE_TEXT
        },
        mimeOptions: {
          'json': 'application/json'
        }
      })
    }
    // search function;
    var searchFunc = function (search_id, content_id) {
      'use strict';
      isfetched = true;
      var datas = JSON.parse(localStorage.getItem('searchJson'));
      // console.log(search_id)
      var input = document.getElementById(search_id);
      var resultContent = document.getElementById(content_id);
      var inputEventFunction = function () {
        var searchText = input.value.trim().toLowerCase();
        var keywords = searchText.split(/[\s\-]+/);
        if (keywords.length > 1) {
          keywords.push(searchText);
        }
        var resultItems = [];
        if (searchText.length > 0) {
          // perform local searching
          datas.forEach(function (data) {
            var isMatch = false;
            var hitCount = 0;
            var searchTextCount = 0;
            var title = data.title
              ? data.title.trim()
              : '';
            var titleInLowerCase = title.toLowerCase();
            var content = data.content
              ? data.content.trim().replace(/<[^>]+>/g, "")
              : '';
            var contentInLowerCase = content.toLowerCase();
            var articleUrl = decodeURIComponent(data.url);

            var date = data.date;
            var dateTime = date.replace(/T/, " ").replace(/.000Z/, "");
            var imgUrl = data.header_img;
            


            var indexOfTitle = [];
            var indexOfContent = [];
            // only match articles with not empty titles
            keywords.forEach(function (keyword) {
              function getIndexByWord(word, text, caseSensitive) {
                var wordLen = word.length;
                if (wordLen === 0) {
                  return [];
                }
                var startPosition = 0,
                  position = [],
                  index = [];
                if (!caseSensitive) {
                  text = text.toLowerCase();
                  word = word.toLowerCase();
                }
                while ((position = text.indexOf(word, startPosition)) > -1) {
                  index.push({position: position, word: word});
                  startPosition = position + wordLen;
                }
                return index;
              }
              indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
              indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
            });
            if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
              isMatch = true;
              hitCount = indexOfTitle.length + indexOfContent.length;
            }
            // show search results
            if (isMatch) {
              // sort index by position of keyword
              [indexOfTitle, indexOfContent].forEach(function (index) {
                index.sort(function (itemLeft, itemRight) {
                  if (itemRight.position !== itemLeft.position) {
                    return itemRight.position - itemLeft.position;
                  } else {
                    return itemLeft.word.length - itemRight.word.length;
                  }
                });
              });
              // merge hits into slices
              function mergeIntoSlice(text, start, end, index) {
                var item = index[index.length - 1];
                var position = item.position;
                var word = item.word;
                var hits = [];
                var searchTextCountInSlice = 0;
                while (position + word.length <= end && index.length != 0) {
                  if (word === searchText) {
                    searchTextCountInSlice++;
                  }
                  hits.push({position: position, length: word.length});
                  var wordEnd = position + word.length;
                  // move to next position of hit
                  index.pop();
                  while (index.length != 0) {
                    item = index[index.length - 1];
                    position = item.position;
                    word = item.word;
                    if (wordEnd > position) {
                      index.pop();
                    } else {
                      break;
                    }
                  }
                }
                searchTextCount += searchTextCountInSlice;
                return {hits: hits, start: start, end: end, searchTextCount: searchTextCountInSlice};
              }
              var slicesOfTitle = [];
              if (indexOfTitle.length != 0) {
                slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
              }
              var slicesOfContent = [];
              while (indexOfContent.length != 0) {
                var item = indexOfContent[indexOfContent.length - 1];
                var position = item.position;
                var word = item.word;
                // cut out 100 characters
                var start = position - 20;
                var end = position + 80;
                if (start < 0) {
                  start = 0;
                }
                if (end < position + word.length) {
                  end = position + word.length;
                }
                if (end > content.length) {
                  end = content.length;
                }
                slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
              }
              // sort slices in content by search text's count and hits' count
              slicesOfContent.sort(function (sliceLeft, sliceRight) {
                if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                  return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                  return sliceRight.hits.length - sliceLeft.hits.length;
                } else {
                  return sliceLeft.start - sliceRight.start;
                }
              });
              // select top N slices in content
              var upperBound = parseInt('1');
              if (upperBound >= 0) {
                slicesOfContent = slicesOfContent.slice(0, upperBound);
              }
              // highlight title and content
              function highlightKeyword(text, slice) {
                var result = '';
                var prevEnd = slice.start;
                slice.hits.forEach(function (hit) {
                  result += text.substring(prevEnd, hit.position);
                  var end = hit.position + hit.length;
                  result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                  prevEnd = end;
                });
                result += text.substring(prevEnd, slice.end);
                return result;
              }
              var resultItem = '';

              // if (slicesOfTitle.length != 0) {   resultItem += "<li><a target='_blank' href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>"; } else {   resultItem += "<li><a target='_blank' href='" +
              // articleUrl + "' class='search-result-title'>" + title + "</a>"; } slicesOfContent.forEach(function (slice) {   resultItem += "<a target='_blank' href='" + articleUrl + "'><p class=\"search-result\">" + highlightKeyword(content, slice) +
              // "...</p></a>"; }); resultItem += "</li>";

              if (slicesOfTitle.length != 0) {
                resultItem += "<a target='_blank' href='" + articleUrl + "' class='search-result'><div class='search-result-left'><div class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</div><time class='search-result-date'>" + dateTime + "</time>";
              } else {
                resultItem += "<a target='_blank' href='" + articleUrl + "' class='search-result'><div class='search-result-left'><div class='search-result-title'>" + title + "</div><time class='search-result-date'>" + dateTime + "</time>";
              }
              slicesOfContent.forEach(function (slice) {
                resultItem += "<p class=\"search-result-content\">" + highlightKeyword(content, slice) + "...</p>";
              });
              resultItem += "</div><div class='search-result-right'><img class='media-image' src='" + imgUrl + "' width='64px' height='48px'></img></div></a>";

              resultItems.push({item: resultItem, searchTextCount: searchTextCount, hitCount: hitCount, id: resultItems.length});
            }
          })
        };

        if (keywords.length === 1 && keywords[0] === "") {
          resultContent.innerHTML = '<div id="no-result"></div>'
        } else if (resultItems.length === 0) {
          resultContent.innerHTML = '<div id="no-result"></div>'
        } else {
          resultItems.sort(function (resultLeft, resultRight) {
            if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
              return resultRight.searchTextCount - resultLeft.searchTextCount;
            } else if (resultLeft.hitCount !== resultRight.hitCount) {
              return resultRight.hitCount - resultLeft.hitCount;
            } else {
              return resultRight.id - resultLeft.id;
            }
          });
          var searchResultList = '<div class=\"search-result-list\">';
          resultItems.forEach(function (result) {
            searchResultList += result.item;
          })
          searchResultList += "</div>";
          resultContent.innerHTML = searchResultList;
        }
      }
      if ('auto' === 'auto') {
        input.addEventListener('input', inputEventFunction);
      } else {
        $('.search-icon').click(inputEventFunction);
        input.addEventListener('keypress', function (event) {
          if (event.keyCode === 13) {
            inputEventFunction();
          }
        });
      }
      // remove loading animation
      $('body').css('overflow', '');
      proceedsearch();
    }
    // handle and trigger popup window;
    $('.popup-trigger').click(function (e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc('local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });
    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function (e) {
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 && $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });

    document.addEventListener('mouseup', (e) => {
      var _con = document.querySelector(".local-search-content");
      if (_con) {
        if (!_con.contains(e.target)) {
          onPopupClose();
        }
      }
    });
  </script>


		
	<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ["$","$"], ["\\(","\\)"] ],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
            processEscapes: true
        }
    });
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax();
        for (var i = 0; i < all.length; ++i)
            all[i].SourceElement().parentNode.className += ' has-jax';
    });
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</body>
</html>
